using System;
using System.Collections.Generic;
using System.IO;
using SpoonCore2.Client;
using SpoonCore2.Message;
using SpoonCore2.Message.Filter.Info;
using SpoonCore2.Service;

namespace SpoonCore2.OverlayNetwork.Pastry.Messages
{
	internal class JoinMessage : AbstractMessage
	{
		private ClientInfo _joinClient;
		private JoinType _type = JoinType.Request;
		private List<ClientInfo> _clientList = new List<ClientInfo>();

		public enum JoinType : byte
		{
			Request,
			Response
		}

		public JoinMessage()
		{
			
		}

		public JoinMessage(ClientInfo joinClient)
		{
			_joinClient = joinClient;
		}

		public ClientInfo JoinInfo
		{
			get { return _joinClient; }
			set { _joinClient = value; }
		}

		public JoinType Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public List<ClientInfo> Clients
		{
			get { return _clientList; }
			set { _clientList = value; }
		}

		public override void GetBytes(BinaryWriter bw)
		{
			_joinClient.GetBytes(bw);
			bw.Write((byte)_type);
			if (_type == JoinType.Response)
			{
				bw.Write(_clientList.Count);
				foreach (ClientInfo info in _clientList)
				{
					info.GetBytes(bw);
				}
			}
		}

		public override void SetBytes(IService service, BinaryReader br)
		{
			_joinClient = new ClientInfo(service, br);
			_type = (JoinType)br.ReadByte();
			if (_type == JoinType.Response)
			{
				int count = br.ReadInt32();
				while (count > 0)
				{
					_clientList.Add(new ClientInfo(service, br));
					count--;
				}
			}
		}
	}
}